package com.wangp.mywrite.s_juc.atomic;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @author farling-wangp
 * @version 1.0
 * @date 2020/10/11 15:33
 */
public class AtomicIntegerFieldUpdaterDemo implements Runnable {
    static Candidate tom = new Candidate();
    static Candidate peter = new Candidate();

    public static AtomicIntegerFieldUpdater<Candidate> scoreUpdater = AtomicIntegerFieldUpdater.newUpdater(Candidate.class, "score");

    @Override
    public void run() {
        for (int i = 0; i < 100000; i++) {
            peter.score++;
            scoreUpdater.getAndIncrement(tom);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        AtomicIntegerFieldUpdaterDemo atomicIntegerFieldUpdaterDemo = new AtomicIntegerFieldUpdaterDemo();
        ;
        Thread t1 = new Thread(atomicIntegerFieldUpdaterDemo);
        Thread t2 = new Thread(atomicIntegerFieldUpdaterDemo);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("普通的变量：" + peter.score);
        System.out.println("升级后的变量：" + tom.score);
    }

    public static class Candidate {
        volatile int score;
    }
}
